package com.dj.shop.util;

import com.dj.shop.poi.mineInterface.IFileInterface;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * @ClassName: FileUtil
 * @Description: 文件工具类
 * @author: luorui
 * @date: 2018年4月26日 上午9:23:19
 */
public class FileUtil {
    public static final Logger log = LoggerFactory.getLogger(FileUtil.class);

    /**
     * @param @param  fileName
     * @param @return
     * @return boolean
     * @Description: 删除单个文件
     * @author luorui
     * @date 2018年4月26日
     */
    public static boolean deleteFile(String fileName) {
        boolean opFlag = true;
        if (!StringUtils.isEmpty(fileName)) {
            File file = new File(fileName);
            // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
            if (file.exists() && file.isFile()) {
                if (file.delete()) {
                    log.info("删除单个文件" + fileName + "成功！");
                } else {
                    opFlag = false;
                    log.error("删除单个文件" + fileName + "失败！");
                }
            } else {
                log.error("删除单个文件失败：" + fileName + "不存在！");
                opFlag = false;
            }
        }
        return opFlag;
    }


    /**
     * 功能描述: java判断文件是否存在
     *
     * @param: strFile
     * @return: boolean
     * @auther: luorui
     * @date: 2018/9/10 20:37
     */
    public static boolean fileIsExists(String strFile) {
        try {
            File f = new File(strFile);
            if (!f.exists()) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }

        return true;
    }

    public static void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }

    /**
     * @return
     * @Author pfl
     * @Description 根据导入的excel文件获取数据
     * @Date 2019/2/21 10:12
     * @Param
     **/
    public synchronized static <T> Set<T> transFile(MultipartFile multipartFile, IFileInterface fileInterface, String[] header, Class<T> clazz) throws IOException {
//        String fileName = multipartFile.getOriginalFilename();
//        // 获取文件后缀
//        String prefix = fileName.substring(fileName.lastIndexOf("."));
//        // 用uuid作为文件名，防止生成的临时文件重复
//        final File excelFile = File.createTempFile(UUID.randomUUID().toString(), prefix);
//        // MultipartFile to File
//        multipartFile.transferTo(excelFile);
//        本地测试使用的
         File excelFile =new File("D:\\software\\asd.xlsx");
        Set<T> set = fileInterface.readFileInfo(excelFile, header, clazz);
        //deleteFile(excelFile);
        return set;
    }


    public static <T> void writeExcel(String[] remarks,String[] heard, List<T> t, OutputStream outputStream) {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("基本数据");
        HSSFRow row = sheet.createRow(0);
        for (int j = 0; j < remarks.length; j++) {
            row.createCell(j).setCellValue(remarks[j]);
        }
        if (t != null && t.size() > 0) {
            for (int i = 0; i < t.size(); i++) {
                row = sheet.createRow(i + 1);
                T tt = t.get(i);
                Field[] fields = tt.getClass().getDeclaredFields();
                for (Field field : fields) {
                    try {
                        String name = field.getName();
                        //int index = com.demo.hospital.common.util.StringUtils.getIndex(heard, name);
                        int index = com.dj.shop.util.StringUtils.getIndex(heard, name);
                        field.setAccessible(true);
                        Object value = field.get(tt);
                        row.createCell(index).setCellValue((String) value);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        try{
            workbook.write(outputStream);// 实现输出
            outputStream.flush();
            outputStream.close();
        }catch (Exception e){
          e.printStackTrace();
        }
    }

    ;


    private final static String excel2003L = ".xls"; // 2003- 版本的excel
    private final static String excel2007U = ".xlsx"; // 2007+ 版本的excel

    public static Workbook getFileType(InputStream inStr, String fileName) throws Exception {
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (inStr == null) {
            if (excel2003L.equals(fileType)) {
                wb = new HSSFWorkbook(); // 2003-
            } else if (excel2007U.equals(fileType)) {
                wb = new XSSFWorkbook(); // 2007+
            } else {
                throw new Exception("解析的文件格式有误！");
            }
        } else {
            if (excel2003L.equals(fileType)) {
                wb = new HSSFWorkbook(inStr); // 2003-
            } else if (excel2007U.equals(fileType)) {
                wb = new XSSFWorkbook(inStr); // 2007+
            } else {
                throw new Exception("解析的文件格式有误！");
            }
        }

        return wb;
    }
}
